﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.CSharp.RuntimeBinder;
using ObjectModel.PowerPoint.RulesModel;

namespace ObjectModel.PowerPoint
{
    public static class COMObjectExtensions
    {
        public static Offsets GetAlignmentOffset(this object o, Alignment alignment)
        {
            // Assume default align-to-centre.
            dynamic d = (dynamic)o;
            double x = d.Width / 2;
            double y = d.Height / 2;

            switch (alignment)
            {
                case Alignment.TopLeft:
                    x = 0;
                    y = 0;
                    break;

                case Alignment.Top:
                    y = 0;
                    break;

                case Alignment.TopRight:
                    x = d.Width;
                    y = 0;
                    break;

                case Alignment.Left:
                    x = 0;
                    break;

                case Alignment.Centre:
                    break;

                case Alignment.Right:
                    x = d.Width;
                    break;

                case Alignment.BottomLeft:
                    x = 0;
                    y = d.Height;
                    break;

                case Alignment.Bottom:
                    y = d.Height;
                    break;

                case Alignment.BottomRight:
                    x = d.Width;
                    y = d.Height;
                    break;
            }

            return new Offsets(x, y);
        }
        
        /// <summary>
        /// Recursively searches for a parent object of specified type.
        /// </summary>
        public static T GetParent<T>(this object o)
        {
            dynamic parent = null;
            try { parent = ((dynamic)o).Parent; }
            catch (COMException) { return default(T); }
            catch (RuntimeBinderException) { return default(T); }

            if (parent is T)
                return parent;

            return parent is T ? parent : GetParent<T>(parent);
        }
    }
}
